package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryById(Long id) throws InterruptedException {

        //1.查redis：
        String deteilJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(deteilJson)) {
            Shop shop = JSONUtil.toBean(deteilJson, Shop.class);
            log.debug("redis查到了！店铺信息已缓存");
            return Result.ok(shop);
        }

        //2. ！锁: 发现redis没有，抢锁!：
        boolean lock = tryLock("lock");
        //！锁：抢到锁，查库：
        if (!lock){
            //！锁：没抢到：返回旧数据或报错，或休眠+递归重试：
            Thread.sleep(50);
            return queryById(id); //尾递归
        }
        //查数据：
        Shop detailDB = getById(id);
        if (detailDB == null){
            return Result.fail("店铺不存在");
        }
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(detailDB), CACHE_SHOP_TTL, TimeUnit.MINUTES);
            log.debug("首次缓存店铺信息");
      return Result.ok(detailDB);

    }
    /**
     * 定义两个方法，获取锁和释放锁
     */

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
